from django.shortcuts import render

from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from drf_spectacular.utils import extend_schema

from .serializers import LoginSerializer, ResetPassSerializer, ProfileSerializer

from .models import Profile


@extend_schema(
    tags=['Account']
)
class ProfileViewset(viewsets.GenericViewSet):

    @extend_schema(
        request=LoginSerializer,
        responses=ProfileSerializer
    )
    @action(methods=['POST'], detail=False)
    def login(self, request):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        profile = Profile.objects.get(user=serializer.validated_data['user'])
        serializer = ProfileSerializer(profile)
        return Response(serializer.data)

    @extend_schema(
        request=ResetPassSerializer,
        responses={204:None}
    )
    @action(methods=['POST'], detail=False)
    def reset_password(self, request):
        serializer = ResetPassSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = request.user
        user.set_password(serializer.validated_data['new_password'])
        user.save()
        return Response({}, status=status.HTTP_204_NO_CONTENT)

    @extend_schema(
        responses=ProfileSerializer
    )
    @action(methods=['GET'], detail=False)
    def profile(self, request):
        profile = Profile.objects.get(user=request.user)
        serializer = ProfileSerializer(profile)
        return Response(serializer.data)

    @extend_schema(
        request=ProfileSerializer,
        responses=ProfileSerializer
    )
    @action(methods=['POST'], detail=False)
    def change(self, request):
        profile = Profile.objects.get(user=request.user)

        serializer = ProfileSerializer(profile, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()


        return Response(serializer.data)
